package com.han.jk_mqtt

import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.mqtt.MqttConnAckMessage
import io.netty.handler.codec.mqtt.MqttConnectMessage
import io.netty.handler.codec.mqtt.MqttConnectPayload
import io.netty.handler.codec.mqtt.MqttConnectVariableHeader
import io.netty.handler.codec.mqtt.MqttFixedHeader
import io.netty.handler.codec.mqtt.MqttMessage
import io.netty.handler.codec.mqtt.MqttMessageBuilders
import io.netty.handler.codec.mqtt.MqttMessageType
import io.netty.handler.codec.mqtt.MqttVersion

class MqttChannelHandler : SimpleChannelInboundHandler<MqttMessage>() {
    override fun channelActive(ctx: ChannelHandlerContext) {
        println("连接准备就绪：-->" + ctx.name())

        val connectMessage = MqttMessageBuilders.connect()
            .clientId("submqtt_111")
            .username("hmz")
            .password("hmz123567")
            .protocolVersion(MqttVersion.MQTT_3_1_1)
            .keepAlive(30)
            .build()
        ctx.channel().writeAndFlush(connectMessage)
    }

    override fun channelRead0(ctx: ChannelHandlerContext?, msg: MqttMessage) {
        val result = msg.decoderResult()
        if (result.isSuccess) {
            val mqttFixHeader = msg.fixedHeader()
            val messageType = mqttFixHeader.messageType()
            when (messageType) {
                MqttMessageType.CONNACK -> {
                    println("连接确认${(msg as MqttConnAckMessage).toString()}")

                }

                MqttMessageType.DISCONNECT -> {
                    TODO()
                }

                MqttMessageType.SUBACK -> {
                    TODO()
                }

                MqttMessageType.UNSUBSCRIBE -> {
                    TODO()
                }

                MqttMessageType.UNSUBACK -> {
                    TODO()
                }

                else -> {

                }
            }
        }else if (result.isFailure) {
            System.err.println("mqtt请求连接异常：\n"+result.cause())
        }
    }


}